package com.hd.trans.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.common.interf.Callback;
import com.hd.trans.common.interf.VoiceComposeListener;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.framework.tools.AppEvents;
import com.hd.trans.framework.tools.HuDunEvent;
import com.hd.trans.homefun.EventCode;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.ui.base.LimitBaseActivity;
import com.hd.trans.utils.TrackerForTrans;
import com.hd.trans.utils.VoicePlaySettingUtil;
import com.hd.trans.utils.VoicePlayUtil;
import com.hd.trans.widgets.VoicePlayView;

public class VoicePlaySettingActivity extends LimitBaseActivity {
    @Override
    protected int getLayoutId() {
        return R.layout.activity_voice_play_setting;
    }

    private static Callback mCallback;
    private static String mTitleName;
    private LinearLayout llOffline, llSpeed, llTimes, llForeign, llChinese;
    private View viewOutside;

    private boolean isTitleVisible;
    private boolean isDestroy;
    private VoicePlayUtil voicePlayUtil;
    private TranslateRecord translateRecord;
    private VoicePlayView voicePlayView;
    private VoicePlayView mCurrentViewVoice;
    private TextView tvContent;

    private float lastTouchY,lastTouchX;
    private long lastTime;

    //open入口
    public static void open(Context context, boolean showTitle) {
        open(context, showTitle, TrackerForTrans.FYSZ);
    }

    //open入口
    public static void open(Context context, boolean showTitle, String titleName) {
        open(context, showTitle, titleName, null);
    }

    //open入口
    public static void open(Context context, boolean showTitle, String titleName, Callback callback) {
        mCallback = callback;
        mTitleName = titleName;
        Intent intent = new Intent(context, VoicePlaySettingActivity.class);
        intent.putExtra("isTitleVisible",showTitle);
        context.startActivity(intent);
        if(showTitle){
            ((Activity)context).overridePendingTransition(R.anim.trans_right_in, R.anim.trans_no_change);
        }else {
            ((Activity)context).overridePendingTransition(R.anim.trans_bottom_in, R.anim.trans_no_change);
        }
    }

    @SuppressLint("UseSwitchCompatOrMaterialCode")
    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        super.initViewsAndEvents(savedInstanceState);
        isTitleVisible = getIntent().getBooleanExtra("isTitleVisible",false);

        TranslationInterior.getTrackerListener().view(mTitleName);

        //top title
        findViewById(R.id.rl_root).setBackgroundColor(isTitleVisible?getResources().getColor(R.color.white):
                getResources().getColor(R.color.transparent));
        findViewById(R.id.tv_title).setVisibility(isTitleVisible?View.GONE:View.VISIBLE);
        findViewById(R.id.iv_close).setVisibility(isTitleVisible?View.GONE:View.VISIBLE);
        findViewById(R.id.ll_title).setVisibility(isTitleVisible?View.VISIBLE:View.GONE);
        String title = mTitleName.equals(TrackerForTrans.WBFYSZ)?TrackerForTrans.SETTING:mTitleName;
        ((TextView)findViewById(R.id.tilte)).setText(title);
        findViewById(R.id.ll_right_title).setVisibility(View.GONE);
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.iv_close).setOnClickListener(this);
        findViewById(R.id.view_outside).setOnClickListener(this);
        findViewById(R.id.ll_voice_play).setOnClickListener(this);
        findViewById(R.id.btn_to_offline).setOnClickListener(this);

        voicePlayView = findViewById(R.id.voice_play_view);
        tvContent = findViewById(R.id.tv_content);
        viewOutside = findViewById(R.id.view_outside);
        if(!isTitleVisible){
            mXHandler.postDelayed(() -> viewOutside.animate()
                    .alpha(0.6f)
                    .setDuration(150)
                    .setListener(null),200);
        }

        Switch switchView = (Switch) findViewById(R.id.switch_view);
        switchView.setChecked(PreferenceMgr.getInstance().getTranslatePreference().getVoiceAuto());
        switchView.setOnCheckedChangeListener((buttonView, isChecked) ->{
            PreferenceMgr.getInstance().getTranslatePreference().saveVoiceAuto(isChecked);
            if(isChecked){
                //埋点
                TranslationInterior.getTrackerListener().click(mTitleName,TrackerForTrans.AUTO_OPEN);
            }else {
                //埋点
                TranslationInterior.getTrackerListener().click(mTitleName,TrackerForTrans.AUTO_CLOSE);
            }
        });

        makeTranslateRecord();


        //离线翻译
        findViewById(R.id.tv_title_offline).setVisibility(mCallback == null?View.GONE:View.VISIBLE);
        llOffline = findViewById(R.id.ll_offline);
        llOffline.setVisibility(mCallback == null?View.GONE:View.VISIBLE);
        for(int i=0;i<llOffline.getChildCount();i++){
            llOffline.getChildAt(i).setOnClickListener(this);
        }
        changeOfflineSwitch(llOffline.getChildAt(PreferenceMgr.getInstance().isOpenOfflineTrans()?0:1));

        //语速
        llSpeed = findViewById(R.id.ll_speed);
        for(int i=0;i<llSpeed.getChildCount();i++){
            llSpeed.getChildAt(i).setOnClickListener(this);
        }
        changeLlSpeedStatus(llSpeed.getChildAt(getIndexBySpeed(PreferenceMgr.getInstance().getTranslatePreference().getVoiceSpeed())));
        //播放次数
        llTimes = findViewById(R.id.ll_times);
        for(int i=0;i<llTimes.getChildCount();i++){
            if(llTimes.getChildAt(i) instanceof TextView){
                llTimes.getChildAt(i).setOnClickListener(this);
            }
        }
        changeLlTimesStatus(llTimes.getChildAt((PreferenceMgr.getInstance().getTranslatePreference().getVoiceTimes()-1)%4));
        //外文人声
        llForeign = findViewById(R.id.ll_foreign);
        for(int i=0;i<llForeign.getChildCount();i++){
            if(llForeign.getChildAt(i) instanceof TextView){
                llForeign.getChildAt(i).setOnClickListener(this);
            }
        }
        changeLlForeignStatus(llForeign.getChildAt(PreferenceMgr.getInstance().getTranslatePreference().getVoiceFLTagIndex()),false);
        //中文人声
        llChinese = findViewById(R.id.ll_chinese);
        for(int i=0;i<llChinese.getChildCount();i++){
            if(llChinese.getChildAt(i) instanceof TextView){
                llChinese.getChildAt(i).setOnClickListener(this);
            }
        }
        changeLlChineseStatus(llChinese.getChildAt(PreferenceMgr.getInstance().getTranslatePreference().getVoiceCNTagIndex()),false);


        //Tts语音播报插件
        voicePlayUtil = VoicePlayUtil.getInstance();

    }

    //是否绑定eventbus
    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    /**
     * eventbus 通知语音播放完成。
     *
     * @param event
     */
    @Override
    protected void onXEventRecv(HuDunEvent<?> event) {
        super.onXEventRecv(event);
        switch (event.getEventCode()) {
            case AppEvents.PLAY_COMPLETE: //播放器播放完成
                if (mCurrentViewVoice != null)
                    mCurrentViewVoice.stopPlay();
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if(action == MotionEvent.ACTION_DOWN){
            lastTime = System.currentTimeMillis();
            lastTouchX = event.getX();
            lastTouchY = event.getY();
        }else if(action == MotionEvent.ACTION_UP){
            if(!isTitleVisible
                    && event.getY() - lastTouchY > 150
                    && event.getX() - lastTouchX < 250
                    && System.currentTimeMillis() - lastTime < 500){
                //关闭
                onBackPressed();
            }
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public void onBackPressed() {
        isDestroy = true;
        finish();
        if(!isTitleVisible){
            overridePendingTransition(R.anim.trans_no_change, R.anim.trans_bottom_out);
        }else {
            overridePendingTransition(R.anim.trans_no_change, R.anim.trans_right_out);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopPlaying();
        if(isDestroy){
            viewOutside.setAlpha(0f);
            voicePlayUtil.destroy();
        }

    }

    private void makeTranslateRecord() {
        translateRecord = new TranslateRecord();
        translateRecord.setContentTranslate(tvContent.getText().toString().trim());
        translateRecord.setContentOrig(tvContent.getText().toString().trim());
        translateRecord.setTriggerTime(System.currentTimeMillis());
        translateRecord.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName("英语"));
        translateRecord.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName("英语"));

    }

    /**
     * 离线翻译开关
     * @param view
     */
    private void changeOfflineSwitch(View view){
        for(int i=0;i<llOffline.getChildCount();i++){
            View child = llOffline.getChildAt(i);
            if(child instanceof TextView){
                TextView textView = (TextView)child;
                if(textView.getId() == view.getId()){
                    textView.setBackgroundTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
                    textView.setTextColor(getResources().getColor(R.color.white));

                    PreferenceMgr.getInstance().setOpenOfflineTrans(i == 0);
                }else {
                    textView.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#F3F6F9")));
                    textView.setTextColor(getResources().getColor(R.color.color_282A43));
                }
            }
        }
    }

    /**
     * 语速改变
     * @param view
     */
    private void changeLlSpeedStatus(View view){
        translateRecord.setTriggerTime(System.currentTimeMillis());
        for(int i=0;i<llSpeed.getChildCount();i++){
            TextView textView = (TextView) llSpeed.getChildAt(i);
            if(textView.getId() == view.getId()){
                textView.setBackgroundTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
                textView.setTextColor(getResources().getColor(R.color.white));

                PreferenceMgr.getInstance().getTranslatePreference().saveVoiceSpeed(getSpeedByIndex(i));
            }else {
                textView.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#F3F6F9")));
                textView.setTextColor(getResources().getColor(R.color.color_282A43));
            }
        }
    }

    /**
     * 索引映射语速
     */
    private int getSpeedByIndex(int index) {
        if(index == 0){//按钮索引0
            return 1;//语速等级1
        }else if(index == 1){
            return 3;
        }else if(index == 2){
            return 5;
        }else if(index == 3){
            return 7;
        }else if(index == 4){
            return 10;
        }

        return 0;
    }

    /**
     * 语速映射索引
     */
    private int getIndexBySpeed(int speed) {
        if(speed == 1){//语速等级1
            return 0;//按钮索引0
        }else if(speed == 3){
            return 1;
        }else if(speed == 5){
            return 2;
        }else if(speed == 7){
            return 3;
        }else if(speed == 10){
            return 4;
        }

        return 0;
    }

    /**
     * 播放次数改变
     * @param view
     */
    private void changeLlTimesStatus(View view){
        for(int i=0;i<llTimes.getChildCount();i++){
            if(llTimes.getChildAt(i) instanceof TextView){
                TextView textView = (TextView) llTimes.getChildAt(i%4);
                if(textView.getId() == view.getId()){
                    textView.setBackgroundTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
                    textView.setTextColor(getResources().getColor(R.color.white));

                    PreferenceMgr.getInstance().getTranslatePreference().saveVoiceTimes(i+1);
                }else {
                    textView.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#F3F6F9")));
                    textView.setTextColor(getResources().getColor(R.color.color_282A43));
                }
            }
        }
    }

    /**
     * 外文人声改变
     * @param view
     */
    private void changeLlForeignStatus(View view, boolean isClicked){
        translateRecord.setTriggerTime(System.currentTimeMillis());
        for(int i=0;i<llForeign.getChildCount();i++){
            if(llForeign.getChildAt(i) instanceof TextView){
                TextView textView = (TextView) llForeign.getChildAt(i);
                if(textView.getId() == view.getId()){
                    textView.setBackgroundTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
                    textView.setTextColor(getResources().getColor(R.color.white));

                    //英文
                    PreferenceMgr.getInstance().getTranslatePreference().saveVoiceFLTag(VoicePlaySettingUtil.getVoiceENTag(i));
                    //其他外文语种
                    PreferenceMgr.getInstance().getTranslatePreference().saveVoiceGender(VoicePlaySettingUtil.getVoiceGender(i));
                    PreferenceMgr.getInstance().getTranslatePreference().saveVoiceFLTagIndex(i);

                    if(isClicked){
                        //埋点
                        TranslationInterior.getTrackerListener().click(mTitleName,
                                VoicePlaySettingUtil.getVoiceENTag(i).split(VoicePlaySettingUtil.SPLIT_STR)[2]);
                    }

                }else {
                    textView.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#F3F6F9")));
                    textView.setTextColor(getResources().getColor(R.color.color_282A43));
                }
            }
        }
    }

    /**
     * 中文人声改变
     * @param view
     */
    private void changeLlChineseStatus(View view, boolean isClicked){
        translateRecord.setTriggerTime(System.currentTimeMillis());
        for(int i=0;i<llChinese.getChildCount();i++){
            if(llChinese.getChildAt(i) instanceof TextView){
                TextView textView = (TextView) llChinese.getChildAt(i);
                if(textView.getId() == view.getId()){
                    textView.setBackgroundTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
                    textView.setTextColor(getResources().getColor(R.color.white));

                    PreferenceMgr.getInstance().getTranslatePreference().saveVoiceCNTag(VoicePlaySettingUtil.getVoiceCNTag(i));
                    PreferenceMgr.getInstance().getTranslatePreference().saveVoiceCNTagIndex(i);

                    if(isClicked){
                        //埋点
                        String[] strings = VoicePlaySettingUtil.getVoiceCNTag(i).split(VoicePlaySettingUtil.SPLIT_STR);
                        TranslationInterior.getTrackerListener().click(mTitleName,strings[strings.length-1]);
                    }

                }else {
                    textView.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#F3F6F9")));
                    textView.setTextColor(getResources().getColor(R.color.color_282A43));
                }
            }
        }
    }

    private void stopPlaying(){
        if(mCurrentViewVoice != null && mCurrentViewVoice.isPlaying()){
            mCurrentViewVoice.stopPlay();
        }
        voicePlayUtil.stopPlay();
    }

    @Override
    public void onViewClick(View v) {
        int id = v.getId();
        if(id != R.id.ll_voice_play){
            stopPlaying();
        }
        if(id == R.id.back
                || id == R.id.view_outside
                || id == R.id.iv_close
        ){
            onBackPressed();
        }else if(id == R.id.tv_offline_1){
            changeOfflineSwitch(v);

            //埋点
            TranslationInterior.getTrackerListener().click(mTitleName,"打开", getString(R.string.offline_setting));
        }else if(id == R.id.tv_offline_2){
            changeOfflineSwitch(v);

            //埋点
            TranslationInterior.getTrackerListener().click(mTitleName,"关闭", getString(R.string.offline_setting));
        }else if(id == R.id.btn_to_offline){
            //埋点
            TranslationInterior.getTrackerListener().click(mTitleName,"离线翻译入口");
            if(mCallback != null){
                mCallback.onCallback();
            }
        }else if(id == R.id.tv_speed_1
                || id == R.id.tv_speed_2
                || id == R.id.tv_speed_3
                || id == R.id.tv_speed_4
                || id == R.id.tv_speed_5
        ){
            changeLlSpeedStatus(v);
            voicePlayUtil.deleteAllTtsFiles();
        }else if(id == R.id.tv_times_1
                || id == R.id.tv_times_2
                || id == R.id.tv_times_3
                || id == R.id.tv_times_4
        ){
            changeLlTimesStatus(v);
        }else if(id == R.id.tv_foreign_1
                || id == R.id.tv_foreign_2
        ){
            changeLlForeignStatus(v,true);
            voicePlayUtil.deleteAllTtsFiles();
        }else if(id == R.id.tv_chinese_1
                || id == R.id.tv_chinese_2
                || id == R.id.tv_chinese_3
        ){
            changeLlChineseStatus(v,true);
            voicePlayUtil.deleteAllTtsFiles();
        }else if(id == R.id.ll_voice_play){
            voicePlayView.performClick();
            //埋点
            TranslationInterior.getTrackerListener().click(mTitleName,TrackerForTrans.SPEED_AUDITION);

            voicePlayback(voicePlayView);
        }
    }

    /**
     * 语音播报
     */
    private void voicePlayback(VoicePlayView mVoicePlayView){

        if(voicePlayUtil.isPlaying()){
            voicePlayUtil.stopPlay();
        }
        if(mCurrentViewVoice != null){
            mCurrentViewVoice.loadingComplete();
            if(mCurrentViewVoice.isPlaying()){
                mCurrentViewVoice.stopPlay();
                if(mCurrentViewVoice == mVoicePlayView)
                    return;
            }
        }

        mCurrentViewVoice = mVoicePlayView;

        if(translateRecord == null
                || translateRecord.getLanguageFrom() == null
                || translateRecord.getLanguageTo() == null
                || TextUtils.isEmpty(translateRecord.getContentTranslate())
                || TextUtils.isEmpty(translateRecord.getContentOrig())){
            return;
        }

        String ttsCode = translateRecord.getIsReverse() ? translateRecord.getLanguageFrom().getTtsCode() : translateRecord.getLanguageTo().getTtsCode();
        voicePlayUtil.executeCompositeFile(ttsCode, translateRecord.getContentTranslate(), new VoiceComposeListener() {
            @Override
            public void onStarting() {

                mCurrentViewVoice.loading();
            }

            @Override
            public void onCompleted(String file, boolean isLocal) {
                mCurrentViewVoice.startPlay();
                voicePlayUtil.startPlay(file);
            }

            @Override
            public void onDownloadFailed() {
                mCurrentViewVoice.loadingFailed();
                voicePlayUtil.stopPlay();
            }
        });
    }

    @NonNull
    @Override
    public EventCode getPageType() {
        return EventCode.VOICE_PLAY_SETTING;
    }
}
